﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
using System.Windows.Forms;

namespace DesktopDOHS.appData
{
    public class Connect
    {
        private OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + @"appData\OMSBD.accdb;Persist Security Info=True");

        private void abreConexao()
        {
            try
            {
                conn.Open(); //Abre a conexão com BD
            }
            catch (Exception e)
            {
                throw new Exception("Erro ao abrir a conexão: " + e.Message);
            }
        }

        private void fechaConexao()
        {
            try
            {
                conn.Close(); //Fecha conexão com BD
            }
            catch (Exception e)
            {
                throw new Exception("Erro ao fechar a conexão: " + e.Message);
            }
        }
        /// <summary>
        /// Executa uma query INSERT ou DELETE considerando os parâmetros (OleDbParameter)
        /// </summary>
        /// <param name="query">INSERT ou DELETE</param>
        public void executa(string query)
        {
            try
            {
                abreConexao();
                OleDbCommand cmd = new OleDbCommand(query, conn);

                cmd.ExecuteNonQuery();//Executa a query no bd

            }
            catch (Exception e)
            { throw new Exception("Erro ao executar query " + query + "\n" + e.Message); }
            finally { fechaConexao(); }
        }

        /// <summary>
        /// Executa uma query SELECT considerando os parâmetros (OleDbParameter)
        /// </summary>
        /// <param name="query">SELECT (Ex. SELECT * FROM...)</param>
        /// <returns>Retorna o DataSet da query executada</returns>
        public DataSet seleciona(string query)
        {
            try
            {
                DataSet ds = new DataSet();
                abreConexao();

                OleDbCommand cmd = new OleDbCommand(query, conn);

                OleDbDataAdapter da = new OleDbDataAdapter(cmd);

                da.Fill(ds); //Preenche DataSet
                return ds; //Retorna o DataSet já contendo os dados
            }
            catch (Exception e)
            { throw new Exception("Erro ao selecionar query " + query + "\n" + e.Message); }
            finally
            { fechaConexao(); }
        }
    }
}
